package service

import (
	"admin-system-go/model"
	"admin-system-go/model/do"
	"admin-system-go/model/dto"
	"admin-system-go/repository"
)

type ResourceGroupService interface {
	QueryResourceGroup(dto dto.ResourceGroupQueryDTO) model.ResponseEntity
	CreateResourceGroup(dto dto.ResourceGroupBaseDTO) model.ResponseEntity
	DelResourceGroup(dto dto.ResourceGroupDelDTO) model.ResponseEntity
}

type resourceGroupServiceImpl struct{}

func (resourceGroupService resourceGroupServiceImpl) QueryResourceGroup(queryDto dto.ResourceGroupQueryDTO) model.ResponseEntity {
	var resourceGroup do.ResourceGroup
	_ = repository.Copy(queryDto, &resourceGroup)
	var resourceGroups []do.ResourceGroup
	pageSize := queryDto.PageSize
	pageNo := queryDto.PageNo
	var total int64
	_ = repository.GetDb().Where(&resourceGroup).Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&resourceGroups)
	var result = make([]dto.ResourceGroupQueryDTO, len(resourceGroups))
	if len(resourceGroups) != 0 {
		_ = repository.GetDb().Model(&do.ResourceGroup{}).Where(&resourceGroup).Count(&total)
	}
	_ = repository.Copy(resourceGroups, result)
	return model.PageEntityModel(result, &model.PageInfo{
		Total:    total,
		PageSize: pageSize,
		PageNo:   pageNo,
	})
}

func (resourceGroupService resourceGroupServiceImpl) CreateResourceGroup(createDto dto.ResourceGroupBaseDTO) model.ResponseEntity {
	var resourceGroup do.ResourceGroup
	_ = repository.Copy(createDto, &resourceGroup)
	tx := repository.GetDb().Where(&do.ResourceGroup{Name: createDto.Name}).Find(&resourceGroup)
	if tx.RowsAffected > 0 {
		return model.FailEntityModel("资源组已经存在")
	}
	tx = repository.GetDb().Create(&resourceGroup)
	return model.BoolEntityModel(tx.RowsAffected == 1, tx.Error)
}

func (resourceGroupService resourceGroupServiceImpl) DelResourceGroup(delDto dto.ResourceGroupDelDTO) model.ResponseEntity {
	tx := repository.GetDb().Delete(&do.ResourceGroup{}, delDto.ResourceGroupIds)
	return model.BoolEntityModel(tx.RowsAffected >= 1, tx.Error)
}
